<template>
  <div>
    <Row style="padding: 5px 0 0 0">
      <Card>
        <VmBtable type="edit" ref="VmBtable"
                  :columns="dataColumns"
                  :data="dataTable"
                  :searchparam="searchParam"
                  :importBtn="false"
                  :downTemplate="false"
                  :exportBtn="false"
                  :searchBtn="false"
                  :batchDelBtn="true"
                  :addBtn="true"
                  :operate="operate"
                  searchText="用户名："
                  cleanText="刷新"
                  v-on:search-change="searchFn"
                  v-on:page-change="pageChangeFn"
                  v-on:restFn="restFn"
                  v-on:addFn="addModal"
                  v-on:batchDelect="batchDelete"
        >
        </VmBtable>
      </Card>
    </Row>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-ok="submitForm" :mask-closable="false"
           width="600" v-on:on-cancel="cancelForm">
      <Form ref="modalForm" :model="modal.form" :label-width="100" label-position="right" :rules="modal.rules">
        <FormItem label="头像" prop="avatarSrc">
          <img style="border-radius: 50%;width: 128px; height: 128px;" :src="modal.form.avatarSrc"
               @click="editAvatar">
        </FormItem>
        <FormItem label="用户名" prop="username">
          <Input v-model="modal.form.username" placeholder="请输入" clearable style="width:90%"/>
        </FormItem>
        <FormItem label="全名" prop="fullName">
          <Input v-model="modal.form.fullName" placeholder="请输入" clearable style="width:90%"/>
        </FormItem>
        <FormItem label="重置密码" prop="pwd" inline>
          <i-switch size="large" v-model="modal.form.restpwd">
            <Icon type="md-checkmark" slot="open"/>
            <Icon type="md-close" slot="close"/>
          </i-switch>
          <Input v-if="modal.form.restpwd" v-model="modal.form.newpwd" placeholder="请输入" type="password" password
                 style="width:50%"/>
        </FormItem>
        <FormItem label="是否锁定">
          <i-switch size="large" v-model="modal.form.isLocked" :true-value="0" :false-value="1">
            <span slot="open">解锁</span>
            <span slot="close">锁定</span>
          </i-switch>
        </FormItem>
        <FormItem label="选择角色" style="width:90%">
          <div style="width:100%">
            <CheckboxGroup v-model="modal.form.roleIds">
              <checkbox v-for="(item,index) in roleList" :key="index" :label="item.id">
                <Icon type="md-people"></Icon>
                <span>{{ item.roleName }}</span>
              </checkbox>
            </CheckboxGroup>
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelForm">取消</Button>
        <Button type="primary" @click="submitForm" :loading="false">确定</Button>
      </div>
    </Modal>
    <Modal v-model="isShowDialog" width="650" title="修改头像" :footer-hide="true">
      <div style="height: 400px;text-align:center;">
        <cropper
          :src="exampleImageSrc"
          crop-button-text="确认提交"
          @on-crop="handleCroped"
        ></cropper>
      </div>
    </Modal>
  </div>
</template>
<script>
import API from '@/libs/api'
import VmBtable from '@/components/vm/vm-btable'
import Cropper from '@/components/cropper'

export default {
  components: {
    VmBtable, Cropper
  },
  data () {
    return {
      apiUrl: 'SysUser',
      replaceWord: '',
      exampleImageSrc: '',
      isShowDialog: false,
      searchParam: {
        current: 1,
        size: 20,
        total: 0,
        username: ''
      },
      dataColumns: [
        { type: 'selection', width: 60, align: 'center' },
        { title: '序号', type: 'index', align: 'center', width: 100 },
        // { title: 'id', align: 'center', key: 'id' },
        { title: '用户名', align: 'center', key: 'username' },
        { title: '全名', align: 'center', key: 'fullName' },
        // { title: 'pwd', align: 'center', key: 'pwd' },
        // { title: 'salt', align: 'center', key: 'salt' },
        // { title: 'isExpired', align: 'center', key: 'isExpired' },
        {
          title: '是否锁定',
          align: 'center',
          key: 'isLocked',
          render: (h, params) => {
            const row = params.row
            return h('Tag', {
              props: {
                color: row.isLocked === 0 ? 'primary' : 'error'
              }
            }, row.isLocked === 0 ? '解锁' : '锁定')
          }
        },
        // { title: 'isDel', align: 'center', key: 'isDel' },
        { title: '创建时间', align: 'center', key: 'createTime' },
        { title: '创建者', align: 'center', key: 'createBy' },
        { title: '修改时间', align: 'center', key: 'updateTime' },
        { title: '修改者', align: 'center', key: 'lastModifiedBy' },
        {
          title: '操作',
          type: 'operation',
          align: 'center',
          width: 130,
          render: (h, param) => {
            let btn = []
            let edit = h('Icon', {
              props: { type: 'md-create', size: '24' },
              style: { color: 'blur', cursor: 'pointer', marginRight: '10px' },
              on: { click: () => this.editModal(param.row) }
            })
            let delBtn = h('Icon', {
              props: { type: 'ios-trash-outline', size: '24' },
              style: { color: 'red', cursor: 'pointer', marginLeft: '5px' },
              on: { click: () => this.delModal(param.row) }
            })
            btn.push(edit)
            btn.push(delBtn)
            return h('div', btn)
          }
        }
      ],
      operate: [],
      dataTable: [],
      modal: {
        title: '',
        visible: false,
        rules: {},
        form: {
          id: '',
          restpwd: false,
          newpwd: '',
          avatarSrc: '',
          roleIds: []
        }
      },
      roleList: []
    }
  },
  methods: {
    editAvatar () {
      this.isShowDialog = true
    },
    handleCroped (blob) {
      this.isShowDialog = false
      const formData = new FormData()
      formData.append('file', blob)
      formData.append('userId', this.modal.form.id)
      API.fileUpload(this.apiUrl + '/updateAvatar', formData).then(res => {
        this.modal.form.avatarSrc = res.data.avatarSrc
      })
    },
    restFn () {
      this.searchParam.current = 1
      this.searchParam.size = 20
      this.queryFn()
    },
    queryFn () {
      API.fetch(this.apiUrl + '/page', this.searchParam).then(
        res => {
          let data = res.data
          this.dataTable = data.records
          this.searchParam.total = data.total
        },
        error => {
          this.$Message.info(error.msg)
        }
      )
    },
    getRoleList () {
      API.fetch('SysRole').then(res => {
        this.roleList = res.data
      },
      error => {
        this.$Message.info(error.msg)
      }
      )
    },
    addModal () {
      this.modal.form.id = ''
      this.modal.form.roleIds = []
      this.modal.form.restpwd = true
      Object.assign(this.modal, {
        title: '新增',
        visible: true,
        form: this.modal.form
      })
    },
    editModal (row) {
      Object.assign(this.modal, {
        title: '编辑',
        visible: true
      })
      Object.assign(this.modal.form, row)
    },
    submitForm () {
      try {
        this.$refs.modalForm.validate(valid => {
          if (valid) {
            if (this.modal.form.id) {
              if (this.modal.form.restpwd && this.modal.form.newpwd.length > 0) {
                Object.assign(this.modal.form, { pwd: this.modal.form.newpwd })
              } else {
                Object.assign(this.modal.form, { pwd: null })
              }
              console.info(this.modal.form)
              API.put(this.apiUrl, this.modal.form).then(
                res => {
                  this.modal.visible = false
                  this.queryFn()
                  this.$refs.modalForm.resetFields()
                  this.modal.form.id = ''
                },
                error => this.$Message.info(error.msg)
              )
            } else {
              API.post(this.apiUrl, this.modal.form).then(
                res => {
                  this.modal.visible = false
                  this.queryFn()
                  this.$refs.modalForm.resetFields()
                  this.modal.form.id = ''
                },
                error => this.$Message.info(error.msg)
              )
            }
          } else {
            return false
          }
        })
      } catch (e) {
        this.$refs.modalForm.resetFields()
      }
    },
    cancelForm () {
      this.modal.visible = false
      if (this.modal.form.id) {
        this.$refs.modalForm.resetFields()
      }
    },
    delModal (row) {
      API.del(this.apiUrl, row.id).then(res => {
        this.queryFn()
      },
      error => this.$Message.info(error.msg))
    },
    batchDelete () {

    },
    pageChangeFn (current) {
      this.searchParam.current = current
      this.queryFn()
    },
    searchFn (value) {
      Object.assign(this.searchParam, {
        username: value
      })
      this.queryFn()
    }
  },
  created () {
  },
  mounted () {
    this.queryFn()
    this.getRoleList()
  }
}
</script>
<style lang="less">
.cropper-example {
  height: 400px;
}
</style>
